import axios from 'axios'
import { ElMessage } from 'element-plus'
const request = axios.create({
  baseURL: import.meta.env.DEV ? '/api6062/service' : '/service',
  timeout: 1000 * 60
})
export const http = {
  setValue (m: any, n: string, v: any) {
    if (v == null) delete m[n]
    else m[n] = v
  },
  toXml (options: any) {
    let reqs ='<request>'
    reqs = reqs + '<head>'
    for(const i in options.head){
      reqs = reqs + '<' + i + '>' + options.head[i]  + '</'+i+'>'
    }
    reqs = reqs + '</head>'
    reqs = reqs + '<fields>'

    for(const i in options.fields){
      reqs = reqs + '<' + i + '><![CDATA[' + options.fields[i] + ']]></' + i + '>'
    }
    reqs += '</fields>'
    reqs += '<tables>'
    if(options.tables!=undefined){
      for(let i = 0; i < options.tables.length; i ++){
        reqs += options.tables[i].toString()
      }
    }
    reqs += '</tables>'
    reqs = reqs + '</request>'
    return reqs
  },
  send<T>(options: any) {
    const trancode = options.trancode
    const xml = this.toXml(options)
    return new Promise<T>(
      resolve => {
        request.post('/' + trancode, xml, {
          headers: {
            'Content-Type': 'text/xml'
          }
        }).then(res => {
          resolve(res.data)
        }).catch(err => {
          ElMessage.error(err.message)
        })
      }  
    )
    
  }
}
// export default <T = any>(config: AxiosRequestConfig) => request(config).then(res => <T>res.data)